#include"mystream.h"


my_file* MyFopen(const char* path , const char* mode)
{
    my_file* pfile = (my_file*)malloc(sizeof(my_file));
    pfile->flag = NONE_FLUSH;
    pfile->bufferSize = 0;
    if(strcmp(mode,"w") == 0)
    {
        pfile->fileno = open(path , O_CREAT | O_WRONLY | O_TRUNC , 0666);
    }
    else if(strcmp(mode,"r") == 0)
    {
        pfile->fileno = open(path , O_CREAT | O_RDONLY , 0666);
    }
    else if(strcmp(mode, "w+") == 0)
    {
        pfile->fileno = open(path , O_CREAT | O_WRONLY | O_APPEND , 0666);
    }

    return pfile;
}

void MyFlush(my_file* pfile)
{
    if(pfile && pfile->bufferSize > 0)
    {
        write(pfile->fileno , pfile->outbuffer , pfile->bufferSize);
        fsync(pfile->fileno);
        pfile->bufferSize = 0;
    }
}

size_t MyWrite(const void* ptr , size_t num , my_file* pfile)
{
    int len = sizeof(ptr);
    memcpy(pfile->outbuffer+pfile->bufferSize , ptr , len);
    pfile->bufferSize += len;
    if(pfile->bufferSize >= MAX_BUFFER || (pfile->outbuffer)[len] == '\n')
    {
        MyFlush(pfile);
    }
    return len;
}

void MyFclose(my_file* pfile)
{
    if(pfile->bufferSize > 0)
    {
        MyFlush(pfile);
    }
    close(pfile->fileno);
    pfile->flag = NONE_FLUSH;
}

int main()
{
    my_file* pfile = MyFopen("file.txt" , "w");
    const char* content = "I will carry all of you";
    MyWrite(content , sizeof(content) , pfile);
    MyFlush(pfile);
    //func();

    // //lib function
    // printf("printf\n");
    // fprintf(stdout , "%s" , "fprintf\n");
    // const char* ch = "my name is fwrite\n";
    // fwrite(ch , 1 , strlen(ch) , stdout);

    // //fflush(stdout);

    // //system call
    // int fd = open("file.txt" , O_CREAT | O_APPEND | O_WRONLY , 0666);
    // const char* ch1 = "my name is write\n";
    // write(fd , ch1 , strlen(ch));

    // fork();
    // close(fd);
    return 0;
}

//test the effect of redir on the type of refresh strategy
// void func()
// {
//     close(1);
//     int fd = open("file.txt" , O_APPEND | O_WRONLY);
//     printf("hahahahha\n");
//     fflush(stdout);
//     close(fd);
// }